package com.lingx.web.api.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import com.lingx.service.LingxService;
import com.lingx.web.api.IApi;
@Component
public class Api9019 extends AbstractDevApi implements IApi{
	@Resource
	private JdbcTemplate jdbcTemplate;
	@Resource
	private LingxService lingxService;
	@Override
	public int getApiCode() {
		return 9019;
	}
	@Override
	public String getApiName() {
		return "获取功能树";
	}
	@Override
	public Map<String, Object> api(Map<String, Object> params) {
		Map<String,Object> ret=IApi.getRetMap(1, "操作成功");
		String fid=IApi.getParamString(params, "fid", "");
		String roleid=IApi.getParamString(params, "role_id", "");
		List<String> checkedKeys=new ArrayList<>();
		List<Map<String,Object>> list=treeFunc(fid,roleid,checkedKeys,this.jdbcTemplate);
		ret.put("data", list);
		ret.put("checkedKeys", checkedKeys);
		return ret;
	}
	public List<Map<String,Object>> treeFunc(String fid,String roleid,List<String> checkedKeys,JdbcTemplate jdbc){
		List<Map<String,Object>> list=jdbc.queryForList("select id,name text from tlingx_func where fid=?  order by name asc",fid);
		boolean b=false;
		for(Map<String,Object> m:list){
			b= jdbc.queryForObject("select count(*) from tlingx_role_func where role_id=? and func_id=?", Integer.class,roleid,m.get("id"))>0;
			if(b)checkedKeys.add(m.get("id").toString());
			m.put("checked",b);
			if("0".equals(fid)) {
				m.put("state","open");
			}else {
				m.put("state","close");
			}
			m.put("leaf", jdbc.queryForObject("select count(*) from tlingx_func where fid=? ", Integer.class,m.get("id"))==0);
			
			List<Map<String,Object>> listsub=treeFunc(m.get("id").toString(),roleid,checkedKeys,jdbc);
			if(listsub.size()>0){
				m.put("children",listsub);
				m.put("checked",false);
				m.put("leaf", false);
				if(b)checkedKeys.remove(m.get("id").toString());
			}else {
				m.put("leaf", true);
				
			}
		}
		return list;
	}

}
